package com.omt.tarjimdinek.web.home;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;

import com.omt.tarjimdinek.context.UserContext;

/**
 * Methods util for home page
 * @author chabane
 *
 */
@Named("homeUtil")
@Scope("session")
public class HomeUtil {

	private boolean doNotShowThisPopupAgain;
	
	/**
	 * Check if a cookie with name in parameter exist on request cookie map
	 * @param aNameCookie
	 * @return true if exist
	 */
	public boolean cookieExist(String aNameCookie){
		FacesContext lContext = FacesContext.getCurrentInstance();
        Map lCookieMap = lContext.getExternalContext().getRequestCookieMap();
        List<Cookie> lCookieList = new ArrayList<Cookie>(lCookieMap.values());
        for(Cookie lCoockie : lCookieList){
        	if(lCoockie.getName().equals(aNameCookie)){
        		return true;
        	}
        }
        return false;
	}
	
	/**
	 * Create a cookie to close a home dialog
	 */
	public void hideHomeDialog(){
		
		if(!cookieExist("hideHomeDialog")){
			ExternalContext lExternalContext = FacesContext.getCurrentInstance().getExternalContext();
			HttpServletResponse lResponse = (HttpServletResponse) lExternalContext.getResponse();
			Cookie lHideHomeDialogCookie = new Cookie("hideHomeDialog", UUID.randomUUID().toString());
			lHideHomeDialogCookie.setMaxAge(31556926); 
			lResponse.addCookie(lHideHomeDialogCookie);
		}
		doNotShowThisPopupAgain = true;
	}

	public boolean isDoNotShowThisPopupAgain() {
		return doNotShowThisPopupAgain;
	}

	public void setDoNotShowThisPopupAgain(boolean doNotShowThisPopupAgain) {
		this.doNotShowThisPopupAgain = doNotShowThisPopupAgain;
	}
}
